<template>
  <el-container style="width: 100%; height: 100vh; display: flex; flex-direction: column;">
    <el-header style="flex-shrink: 0;">
      <h1>磁盘监控系统</h1>
    </el-header>

    <el-main style="padding: 20px; flex-grow: 1; display: flex; flex-direction: column;">
      <!-- 图表区域 -->
      <el-row :gutter="20" style="flex: 1; min-height: 300px;">
        <el-col :span="12" style="height: 100%;">
          <div class="chart-container" ref="pieChartRef"></div>
        </el-col>
        <el-col :span="12" style="height: 100%;">
          <div class="chart-container" ref="barChartRef"></div>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-row style="margin-top: 20px;">
        <el-col :span="24">
          <el-table :data="diskData" border v-loading="loading" height="240" style="width: 100%;">
            <el-table-column prop="deviceName" label="设备名称" />
            <el-table-column prop="fileSystem" label="文件系统" />
            <el-table-column prop="totalSpace" label="总容量" />
            <el-table-column prop="freeSpace" label="可用空间" />
            <el-table-column prop="diskUsage" label="使用率">
              <template #default="scope">
                <el-progress
                    :percentage="parseFloat(scope.row.diskUsage)"
                    :status="getProgressStatus(scope.row.diskUsage)"
                />
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20]"
                :total="totalElements"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

// 数据相关
const diskData = ref([]);
const totalElements = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const apiUrl = '/api/disk-info';

// 图表引用
const pieChartRef = ref(null);
const barChartRef = ref(null);
let pieChart = null;
let barChart = null;

// 获取磁盘数据
const fetchDiskData = async () => {
  try {
    loading.value = true;
    const response = await fetch(`${apiUrl}?page=${currentPage.value - 1}&size=${pageSize.value}`, {
      method: 'GET',
      mode: 'cors',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const responseData = await response.json();
    const items = Array.isArray(responseData.data) ? responseData.data : responseData.content || [];
    const total = responseData.totalElements || responseData.total || items.length;

    diskData.value = items;
    totalElements.value = total;
  } catch (error) {
    console.error('获取磁盘数据失败:', error);
    ElMessage.error(`获取数据失败: ${error.message}`);
  } finally {
    loading.value = false;
  }
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchDiskData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchDiskData();
};

// 进度条状态
const getProgressStatus = (usage) => {
  const val = parseFloat(usage.toString().replace('%', ''));
  if (val > 80) return 'exception';
  if (val > 60) return 'warning';
  return 'success';
};

// 初始化图表
const initCharts = () => {
  pieChart = echarts.init(pieChartRef.value);
  barChart = echarts.init(barChartRef.value);
};

// 更新图表
const updateCharts = () => {
  if (!diskData.value.length || !pieChart || !barChart) return;

  // 饼图数据
  const pieData = diskData.value.map(item => ({
    name: item.deviceName,
    value: parseFloat(item.diskUsage.toString().replace('%', ''))
  }));

  pieChart.setOption({
    title: { text: '磁盘使用率分布', left: 'center' },
    tooltip: { trigger: 'item' },
    series: [{
      type: 'pie',
      radius: '60%',
      data: pieData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  // 柱状图数据
  const barXData = diskData.value.map(item => item.deviceName);
  const totalSpaceData = diskData.value.map(item => formatSizeToGB(item.totalSpace));
  const freeSpaceData = diskData.value.map(item => formatSizeToGB(item.freeSpace));

  barChart.setOption({
    title: { text: '磁盘容量对比 (GB)', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { data: ['总容量', '可用空间'], top: 30 },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { type: 'category', data: barXData },
    yAxis: { type: 'value', name: 'GB' },
    series: [
      { name: '总容量', type: 'bar', data: totalSpaceData },
      { name: '可用空间', type: 'bar', data: freeSpaceData }
    ]
  });
};

// 单位转换：统一转为 GB
const formatSizeToGB = (sizeStr) => {
  if (!sizeStr) return 0;
  const size = parseFloat(sizeStr);
  const unit = sizeStr.replace(/[\d\s.]/g, '').toUpperCase();
  switch (unit) {
    case 'TB': return size * 1024;
    case 'GB': return size;
    case 'MB': return size / 1024;
    case 'KB': return size / (1024 * 1024);
    default: return size;
  }
};

// 生命周期
onMounted(() => {
  initCharts();
  fetchDiskData();

  window.addEventListener('resize', () => {
    pieChart?.resize();
    barChart?.resize();
  });
});

// 监听数据变化更新图表
watch(diskData, async (newVal) => {
  if (newVal.length) {
    await nextTick();
    updateCharts();
    pieChart?.resize();
    barChart?.resize();
  }
}, { immediate: true });
</script>

<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  line-height: 60px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  background: #fff;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>
